# from neo4j import GraphDatabase
#
# class Neo4jUtils:
#     def __init__(self, uri, user, password):
#         """
#         初始化 Neo4j 连接
#         :param uri: Neo4j 数据库地址，例如 'bolt://localhost:7687'
#         :param user: 用户名
#         :param password: 密码
#         """
#         self._driver = GraphDatabase.driver(uri, auth=(user, password))
#
#     def close(self):
#         """
#         关闭数据库连接
#         """
#         self._driver.close()
#
#     def run_query(self, query, parameters=None):
#         """
#         执行 Cypher 查询
#         :param query: Cypher 查询语句
#         :param parameters: 查询参数
#         :return: 查询结果
#         """
#         with self._driver.session() as session:
#             result = session.run(query, parameters)
#             return list(result)  # 将结果转换为列表
#
#     def get_node_by_name(self, name):
#         """
#         根据节点名称查询节点信息
#         :param name: 节点名称
#         :return: 节点信息
#         """
#         query = """
#         MATCH (n {name: $name})
#         RETURN n
#         """
#         return self.run_query(query, parameters={"name": name})
#
#     def get_relationships(self, node1, node2):
#         """
#         查询两个节点之间的关系
#         :param node1: 节点1名称
#         :param node2: 节点2名称
#         :return: 关系信息
#         """
#         query = """
#         MATCH (n1 {name: $node1})-[r]->(n2 {name: $node2})
#         RETURN r
#         """
#         return self.run_query(query, parameters={"node1": node1, "node2": node2})

from neo4j import GraphDatabase

class Neo4jUtils:
    def __init__(self, uri, user, password):
        """
        初始化 Neo4j 连接
        :param uri: Neo4j 数据库地址，例如 'bolt://localhost:7687'
        :param user: 用户名
        :param password: 密码
        """
        self._driver = GraphDatabase.driver(uri, auth=(user, password))

    def close(self):
        """
        关闭数据库连接
        """
        self._driver.close()

    def run_query(self, query, parameters=None):
        """
        执行 Cypher 查询
        :param query: Cypher 查询语句
        :param parameters: 查询参数
        :return: 查询结果
        """
        with self._driver.session() as session:
            result = session.run(query, parameters)
            return list(result)  # 将结果转换为列表

    def get_answer(self, relation: str, direction: str, entity: str) -> list :
        """
        通用查询方法（新版）
        :param relation: 关系类型，来自配置文件的'relation'字段
        :param direction: 关系方向，来自配置文件的'direction'字段（in/out）
        :param entity: 查询主体名称
        :return: 查询结果列表
        """
        # 参数校验
        if direction not in ["in", "out"] :
            raise ValueError(f"无效的关系方向: {direction}，仅支持 in/out")

        # 动态生成Cypher查询
        cypher_template = """
        MATCH (n1 {{name: $entity}}){relation}(n2)
        RETURN n2.name AS name
        """

        # 根据方向生成关系语法
        relation_arrow = {
            "out" : f"-[:{relation}]->",
            "in" : f"<-[:{relation}]-"
        }[direction]

        # 安全拼接查询语句（因relation来自配置文件白名单，无需防注入）
        query = cypher_template.format(relation=relation_arrow)

        # 执行查询
        result = self.run_query(query, parameters={"entity" : entity})
        return [record["name"] for record in result]
if __name__ == "__main__":
    # 初始化 Neo4j 连接
    neo4j_utils = Neo4jUtils(uri="bolt://localhost:7687", user="neo4j", password="12345678")
    try:
        # 查询萧炎的妻子
        wife_names = neo4j_utils.get_answer("妻子", "萧炎", )
        print(f"萧炎的妻子有：{wife_names}")
        # 查询中州的势力
        force_names = neo4j_utils.get_answer("势力", "中州")
        print(f"中州的势力有：{force_names}")
    except Exception as e:
        print(f"查询出错：{e}")

    # 关闭连接
    neo4j_utils.close()
